package org.swingplus.core.util;

import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.swingplus.core.annotation.widget.Frame;
import org.swingplus.core.bean.MetaData;
import org.swingplus.core.constant.bean.ScopeConstant;
import org.swingplus.core.factory.WidgetFactroy;
import org.swingplus.core.utils.StringUtil;
import org.swingplus.core.widget.WidgetActvity;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//import

public final class CssManageUtil {

	private static final Logger logger= LoggerFactory.getLogger(CssManageUtil.class);
	
 

	/**
     * 获取指定文件下面的RequestMapping方法保存在mapp中
     *
     * @param packageName
     * @return
     */
//    public static Map<String, ExecutorBean> getFrameClass(String packageName) {
//        Reflections reflections = new Reflections(packageName);
//        Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(Frame.class);
//
//        // 存放url和ExecutorBean的对应关系
//        Map<String, ExecutorBean> mapp = new HashMap<String, ExecutorBean>();
//        for (Class classes : classesList) {
//            //得到该类下面的所有方法
//            Method[] methods = classes.getDeclaredMethods();
//
//            for (Method method : methods) {
//                //得到该类下面的RequestMapping注解
//                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
//                if (null != requestMapping) {
//                    ExecutorBean executorBean = new ExecutorBean();
//                    try {
//                        executorBean.setObject(classes.newInstance());
//                    } catch (InstantiationException e) {
//                        e.printStackTrace();
//                    } catch (IllegalAccessException e) {
//                        e.printStackTrace();
//                    }
//                    executorBean.setMethod(method);
//                    mapp.put(requestMapping.value(), executorBean);
//
//                }
//            }
//        }
//        return mapp;
//    }


	public static Annotation[] annotationsType(Class clazz) {
		Annotation[] annotationsByType = clazz.getDeclaredAnnotations();
        return annotationsByType;

	}
	/**
	 *   实例 中 使用注解 的 属性 集合
	 * @param obj 实例
	 * @param clazz 注解
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<Field,Annotation[]> fieldByAnnotationsType(Object obj,Class clazz) {
		Map<Field,Annotation[]> map=new HashMap<>();
		Field[] fields= obj.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			Annotation[] annotations= field.getDeclaredAnnotations();
			if(annotations!=null&&annotations.length!=0) {
				for (int j = 0; j < annotations.length; j++) {
					String simpleName=annotations[j].annotationType().getSimpleName();
					if(simpleName.equals(clazz.getSimpleName())) {
						map.put(field, annotations);
					}
				}
				
//				if(annotation instanceof CustomAnnotation){
//		            CustomAnnotation customAnnotation = (CustomAnnotation) annotation;
//		            System.out.println("name: " + customAnnotation.name());
//		            System.out.println("value: " + customAnnotation.value());
//		         } 
				
			}
		}
        return map;

	}
	@SuppressWarnings("unchecked")
	public static Map<Field,Annotation[]> fieldAnnotationsType(Object obj) {
		Map<Field,Annotation[]> map=new HashMap<>();
		Field[] fields= obj.getClass().getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			map.put(field, field.getDeclaredAnnotations());
//			
		}
        return map;

	}

    public static Map<String,String > getFrameType(String packageName) {
        Reflections reflections = new Reflections(packageName);
        Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(Frame.class);

        // 存放url和ExecutorBean的对应关系
        Map<String,String> mapp = new HashMap<String,String>();
        for (Class<?> classes : classesList) {
        	System.out.println(classes.getName());
        	Object ff=WidgetFactroy.create(classes.getName());
        	Method setVisibleMethod=null;
        	try {
				 setVisibleMethod=ff.getClass().getMethod("setVisible", new Class[] {boolean.class});
			} catch (NoSuchMethodException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			} catch (SecurityException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
        	
            //得到该类下面的所有方法
            @SuppressWarnings("unused")
			Method[] methods = classes.getDeclaredMethods();
            Field[] fields = classes.getDeclaredFields();
            for (Field field : fields) {
            	if("controlPanel".equals(field.getName())) {
            		field.setAccessible(true);
            		try {
            			Object obj=field.get(ff);
						if(null==field.get(ff)) {
							obj=WidgetFactroy.create(field.getType().toString().split(" ")[1]);
//		            		JPanel jPanel=(JPanel)ssdd;
						}
						WidgetActvity.onCreate(obj,field);
		                	System.out.println("Object create:"+obj);
		                	try {
								field.set(ff, obj);
							} catch (IllegalArgumentException | IllegalAccessException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
		                	field.setAccessible(false);
		                    //得到该类下面的RequestMapping注解
		                	System.out.println("fieldName:"+field.getName());
		                	System.out.println("fieldType:"+field.getType() );
		                	System.out.println("fieldClass:"+field.getClass() );
		                	System.out.println("fieldModifier:"+field.getModifiers() );
		                	try {
								setVisibleMethod.invoke(ff, true);
							} catch (InvocationTargetException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					} catch (IllegalArgumentException | IllegalAccessException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
            		
            		
            		
            	}
//            	field.
                Annotation[] annotations = field.getAnnotations();
                for (Annotation annotation : annotations) {
                	 System.out.println("annotationType:"+annotation.annotationType().getName());
//                	 System.out.println(annotation.getName());
				}
            }
        }
        return mapp;
    }
    
    @SuppressWarnings("rawtypes")
	public static MetaData getAnnotationType(String packageName,Class clazz) {
		
		MetaData meteData=new MetaData();
		Map<Field,Annotation[]> map=new HashMap<>();
        Reflections reflections = new Reflections(packageName);
        @SuppressWarnings("unchecked")
		Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(clazz);
        // 存放url和ExecutorBean的对应关系
        for (Class<?> classes : classesList) {
        	String simpleName=clazz.getSimpleName();
        	String name=clazz.getName();
			Annotation[] annotationsType=classes.getDeclaredAnnotations();
			meteData.setAnnotationsType(annotationsType);
			logger.info("discover Type Annotation:[type:{},typeClasspath:{},typeAnnotationSizes:{}]",classes.getSimpleName(),classes.getTypeName(),annotationsType.length);
        	System.out.println("discover Annotation: "+ simpleName +" size:"+classesList.size() + " classpath: "+name);
        	logger.info("discover Annotation {} size: {} classpath: {}",clazz,classesList.size(),name);
//        	System.out.println(classes.getName());
        	Object obj=WidgetFactroy.create(classes.getName());
			Field[] fields = classes.getDeclaredFields();
			for (Field field : fields) {
                //exists Annotation choject
//				field.
				Annotation[] annotations = field.getAnnotations();
			    if(null!=annotations&&annotations.length!=0){
					for (Annotation annotation : annotations) {
						System.out.println("discover "+field.getName() +" annotationType:"+annotation.annotationType().getName());
//                	 System.out.println(annotation.getName());
					}
					field.setAccessible(true);
					try {
						Object fieldObj=field.get(obj);
						String fieldType=field.getType().getName();
						if(null==fieldObj) {
							fieldObj=WidgetFactroy.create(field.getType().getName());
//		            		JPanel jPanel=(JPanel)ssdd;
						}
						WidgetActvity.onCreate(fieldObj,field);
						System.out.println("Object create:"+fieldObj);
						try {
							field.set(obj, fieldObj);
						} catch (IllegalArgumentException | IllegalAccessException e) {
							e.printStackTrace();
						}
						field.setAccessible(false);
						//得到该类下面的RequestMapping注解
						System.out.println("field[Name:"+field.getName()+" Type:"+fieldType+" Modifier:"+ field.getModifiers());
						logger.info("field[Name:{} Type:{} Modifier:{}"+field.getName(),fieldType,field.getModifiers());
						map.put(field, annotations);
//						try {
////							setVisibleMethod.invoke(ff, true);
//						} catch (InvocationTargetException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
					} catch (IllegalArgumentException | IllegalAccessException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}

			    meteData.setInstance(obj);
			    meteData.setMap(map);
				}

//			}

        }
//            //得到该类下面的所有方法
//            @SuppressWarnings("unused")
//			Method[] methods = classes.getDeclaredMethods();
//            Field[] fields = classes.getDeclaredFields();
//            for (Field field : fields) {
//            	if("controlPanel".equals(field.getName())) {
//            		//Object ssdd=WidgetFactroy.create(field.getType().toString().split(" ")[1]);
//            		JPanel jPanel=(JPanel)ssdd;
//            		WidgetActvity.onCreate(ssdd,field);
//                	System.out.println("Object create:"+jPanel);
//                	field.setAccessible(true);
//                	try {
//						field.set(ff, jPanel);
//					} catch (IllegalArgumentException | IllegalAccessException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//                	
//                    //得到该类下面的RequestMapping注解
//                	System.out.println("fieldName:"+field.getName());
//                	System.out.println("fieldType:"+field.getType() );
//                	System.out.println("fieldClass:"+field.getClass() );
//                	System.out.println("fieldModifier:"+field.getModifiers() );
//            	}
////            	field.
//                Annotation[] annotations = field.getAnnotations();
//                for (Annotation annotation : annotations) {
//                	 System.out.println("annotationType:"+annotation.annotationType().getName());
////                	 System.out.println(annotation.getName());
//				}
// 
//            }
//        }
        
        
        return meteData;
    }
    
    
    
    @SuppressWarnings("rawtypes")
	public static Map<String,Object> createByAnnotationType(String packageName,Class clazz) {
        Reflections reflections = new Reflections(packageName);
        @SuppressWarnings("unchecked")
		Set<Class<?>> classesList = reflections.getTypesAnnotatedWith(clazz);
        // 存放url和ExecutorBean的对应关系
        Map<String,Object> objMap = new HashMap<>();
        
        for (Class<?> classes : classesList) {
//        	String simpleName=clazz.getSimpleName();
        	
        	String classesSimpleName=classes.getSimpleName();
        	String classesName=classes.getName();
        	String simpleName=clazz.getSimpleName();
        	
        	String name=clazz.getName();
        	System.out.println("discover Annotation: "+ simpleName +" size:"+classesList.size() + " classpath: "+name);
        	logger.info("discover Annotation {} size: {} classpath: {}",clazz,classesList.size(),name);
        	Annotation[] annotationsClass = classes.getAnnotations();
        	System.out.println("discover "+classesSimpleName+ " annotations size: " +annotationsClass.length);
        	for (Annotation annotation : annotationsClass) {
        		System.out.print("       "+annotation.annotationType().getSimpleName()+" ");
//        		annotation
			}
        	if(annotationsClass.length!=0) {
				System.out.println();
			}
//        	Scope scope = classes.getAnnotation(Scope.class);
        	Object obj= null;
//        	if(scope!=null) {
//        		obj=WidgetFactroy.create(classesName,classesSimpleName,scope.value());
//        	}else {
        		obj=WidgetFactroy.create(classesName,classesSimpleName,ScopeConstant.singleton);
//        	}
			Field[] fields = classes.getDeclaredFields();
			for (Field field : fields) {
                //exists Annotation choject
//				field.
				Annotation[] annotations = field.getAnnotations();
			    if(null!=annotations&&annotations.length!=0){
					for (Annotation annotation : annotations) {
						System.out.println("discover "+field.getName() +" annotationType:"+annotation.annotationType().getName());
//                	 System.out.println(annotation.getName());
					}
			    }
			}
			objMap.put(StringUtil.lowerFirst(classesSimpleName),obj);

        }
 
        return objMap;
    }
    
    
}